var debug = require('debug')('consutant:index_router'),
    wechat = require('wechat'),
    settings = require('../config'),
    wechat_util = require('../utils/wechatutil'),
    models = require("../models"),
    User = models.User,
    Message = models.Message;
var request = require('request');
    Session = models.WCSession;
var sign=require('./sign');

module.exports = function(app) {
    app.get("/wcpay/socket", function(req, res) {
//        if(req.query.state==1){
//            res.render('socket',{openid:'sdfsdfsdfsdf',nickname:'some',headimgurl:'sdfsdf',room:'room1',err:1});
//        }
        var room=req.query.state;
        new wechat_util().getOAuth(req.query.code,function(oauth,result){
            if(result.errcode){
                var error={};
                    error.status="错误代码: "+result.errcode;
                res.render('error',{message:"连接错误，请重新用微信扫描二维码。",error:error});
            }else{
                var openid = result.openid;
                var access_token =result.access_token;
                new wechat_util().getAPI(function (api) {
                    api.getUserInfo1(openid, access_token,function (err, uresult,re) {
                        if (uresult) {
                            var nickname = uresult.nickname;
                            var imgurl=uresult.headimgurl;
                            debug("this nickname is ", uresult.nickname);
                            res.cookie("user", nickname, {maxAge: 1000*60*60*24*30});
                            new User().findopenidBygroup(openid,function(err,data){
                                if(data==0){
                                    new User({
                                        wcopenid: openid,
                                        user_group: "80",
                                        createtime: new Date(),
                                        nickname:nickname,
                                        headimgurl:imgurl
                                    }).save();
                                    res.render('socket',{openid:openid,nickname:nickname,headimgurl:imgurl,room:room,err:1});
                                }else if(data==1){
                                    if(!nickname&&!imgurl){
                                        var opt={};
                                        opt.nickname=nickname;
                                        opt.headimgurl=imgurl;
                                        new User().updateHtmlUserByOpneId(openid,opt,function(err){
                                            if(err){
                                                debug("updateHtmlUserByOpneId fail", err);
                                            }
                                        });
                                        res.render('socket',{openid:openid,nickname:nickname,headimgurl:imgurl,room:room,err:1});
                                    }else{
                                        res.render('socket',{openid:openid,nickname:nickname,headimgurl:imgurl,room:room,err:1});
                                    }
                                    res.render('socket',{openid:openid,nickname:nickname,headimgurl:imgurl,room:room,err:1});
                                }
                                if(err){
                                    res.render('socket',{openid:openid,nickname:nickname,headimgurl:imgurl,room:room,err:1});
                                }
                            });

                        } else {
                            debug("initattentionUser find no user");
                        }
                    });
                });
            }
        });
    });
    app.get('/video',function(req,res){
        var url=req.query.url;
        console.log(url);
        if(req.session.ticket){
            console.log('session !');
        }else{
            request.get({url:'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+settings.wc_appid+'&secret='+settings.wc_appsecret},function(error, httpResponse, body){
                console.log("222222"+body+"33333"+error);
                var token=JSON.parse(body).access_token;
                request.get({url:'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+token+'&type=jsapi'},function(error, httpResponse, body) {
                    console.log("------"+body+"-------"+error);
                    var ticket=JSON.parse(body).ticket;
                    req.session.ticket=ticket;
                    var signs=sign(req.session.ticket,url);
                    var datas={};
                    datas.signs=signs;
                    datas.token=token;
                    res.send(datas);
                });
            });
        }
    });
    app.get('/wxmedia',function(req,res){
        var token=req.query.token;
        console.log(token);
        var serverid=req.query.serverid;
        request.get({url:'http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='+token+'&media_id='+serverid},function(error, httpResponse, body){
            console.log(body);
            res.send(body);
        });
    });
}